package com.devshephard.springcloud.controller;

import com.devshephard.springcloud.config.customLoadBanlance.CustomLoadBanlance;
import com.devshephard.springcloud.entities.CommonResult;
import com.devshephard.springcloud.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.CountDownLatch;

@RestController
@Slf4j
public class OrderController {

    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    DiscoveryClient discoveryClient;

    @Resource
    CustomLoadBanlance customLoadBanlance;

    @PostMapping("/consumer/payment/create")
    @ResponseBody
    public CommonResult<Payment> create(@RequestBody Payment payment){
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create",payment,CommonResult.class);
    }

    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
        List<ClientHttpRequestInterceptor> clientHttpRequestInterceptorList =  restTemplate.getInterceptors();
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
    }

    @GetMapping("/consumer/testLb")
    @ResponseBody
    public Integer testLb(){

        CountDownLatch countDownLatch = new CountDownLatch(1000);

        List<ServiceInstance> instanceList = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        Vector<Integer> checkList = new Vector<>();

        Integer index = customLoadBanlance.getServerIndex(instanceList);
        return instanceList.get(index).getPort();

    }


}
